<?php

namespace app\api\controller;

use app\common\model\UserAddress;
use ba\Tree;
use think\facade\Log;
use Throwable;
use think\facade\Db;
use think\facade\Config;
use app\common\controller\Frontend;
use app\common\library\token\TokenExpirationException;
use app\ExceptionHandle;

class Address extends Frontend
{
    protected array $noNeedPermission = ['*'];
    protected $model;

    public function initialize (): void
    {
        parent::initialize();
        $this->model = Db::table("ba_user_address");
    }

    public function add (): void
    {
        $params = $this->request->post();
        if ($params['is_default'] == 1) {
            $this->model->where('user_id', $this->auth->id)->update(['is_default' => 0]);
        }

        #validate验证$params参数
        $validate = new \app\api\validate\UserAddress();
        if (!$validate->check($params)) {
            $this->error($validate->getError());
        }

        $tel = $params['contacts_tel'];
        $code = $params['code'];


        #验证短信验证码是否正确
        try {
            sms_check($tel, $code, 'user_address');
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }


        $save = $this->model
            ->insert([
                'user_id'      => $this->auth->id,
                'address'      => $params['address'],
                'house_number' => $params['house_number'],
                'contacts'     => $params['contacts'],
                'contacts_tel' => $params['contacts_tel'],
                'is_default'   => $params['is_default'] ?? 0,
                'create_time'  => date("Y-m-d H:i:s", time()),
                'lng'          => $params['lng'],
                'lat'          => $params['lat'],
            ]);
        if ($save) {
            $this->success("添加成功");
        }
        $this->error("添加失败");
    }


    /**
     * 地址列表
     * @return void
     */
    public function list ()
    {
        Log::info('address-' . $this->auth->getToken());
        $list = $this->model
            ->where('user_id', $this->auth->id)
            ->select();
        $this->success("", $list);
    }


    /**
     * 删除地址
     * @param integer $id 地址id
     * @return void
     */
    public function delete ()
    {
        $id = $this->request->get('id');
        $delete = $this->model
            ->where('id', $id)
            ->where('user_id', $this->auth->id)
            ->delete();
        if ($delete) {
            $this->success("删除成功");
        }
        $this->error("删除失败");
    }

    /**
     * 编辑地址
     * @param integer $id 地址id
     * @param string $address 地址
     * @param string $house_number 门牌号
     * @param string $contacts 联系人
     * @param string $contacts_tel 联系电话
     * @param integer $is_default 是否默认地址
     * @return void
     */
    public function edit ()
    {
        $params = $this->request->post();

        $id = $params['id'] ?? 0;

        foreach ($params as $key => $value) {
            if (empty($value) && $value != 0) {
                unset($params[$key]);
            }
        }
        if ($params['is_default'] == 1) {
            $this->model->where('user_id', $this->auth->id)->update(['is_default' => 0]);
        }
        $info = UserAddress::where('id', $id)
            ->where('user_id', $this->auth->id)
            ->find();
        if (!$info) {
            $this->error("地址不存在");
        }
        #验证短信验证码是否正确
        try {
            sms_check($params['contacts_tel'], $params['code'], 'user_address');
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }


        $info->allowField(['address', 'house_number', 'contacts', 'contacts_tel', 'is_default', 'lng', 'lat']);

        if ($info->save($params)) {
            $this->success("编辑成功");
        }
        $this->error("编辑失败");
    }

}